package client

import (
	"bytes"
	"encoding/json"
	// "image"
	"io"
	"io/ioutil"
	"mime/multipart"
	"net/http"
	"task/form"
	"task/logger"
	"task/picture"
	"time"
)

/*
send img by http for identify
*/
func SendImg(img *picture.SmallImg, url string) (result *form.IdentifyResp) {
	result = new(form.IdentifyResp)
	result.Code = 99

	bodyBuf := &bytes.Buffer{}
	bodyWriter := multipart.NewWriter(bodyBuf)
	// buf := new(bytes.Buffer)
	// if format == "png" {
	// 	err = png.Encode(buf, img.Img)
	// } else {
	// 	panic("bad image png")
	// }
	buf, err := img.Encode()
	if err != nil {
		logger.Error("Encode img err", err)
		return
	}
	fileWriter, err := bodyWriter.CreateFormFile("pic", "pic")
	if err != nil {
		logger.Error("error writing to buffer", err)
		return
	}

	_, err = io.Copy(fileWriter, buf)
	if err != nil {
		logger.Error("io copy error:", err)
		return
	}

	contentType := bodyWriter.FormDataContentType()
	bodyWriter.Close()

	c := &http.Client{
		Timeout: 10 * time.Second,
	}

	resp, err := c.Post(url, contentType, bodyBuf)
	if err != nil {
		logger.Error("http post error:", err)
		return
	}
	defer resp.Body.Close()
	resp_body, err := ioutil.ReadAll(resp.Body)
	jsonstr := bytes.NewBuffer(resp_body).String()
	if err := json.Unmarshal([]byte(jsonstr), &result); err != nil {
		logger.Error("json load err:", img.ImgNo, jsonstr, "\terr:", err)
		result.Code = 99
	}
	return
}

/*
send callback request
*/
func SendCallBack(url string, send_url string, response *form.ResponseData) {
	c := &http.Client{
		Timeout: 3 * time.Second,
	}

	result, err := json.Marshal(response)
	if err != nil {
		logger.Error("json Marshal err", err)
		return
	}

	// c.Post(url, "application/json", result)
	body_type := "application/json;charset=utf-8"
	reqData := bytes.NewBuffer([]byte(result))
	resp, err := c.Post(url, body_type, reqData)
	if err != nil {
		logger.Error("http post error:", err)
		return
	}
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)
	jsonstr := bytes.NewBuffer(body).String()
	logger.Info("callback_url", url, "\timg_url:", send_url, "\tcallback:", bytes.NewBuffer([]byte(result)).String())
	logger.Info("callback_url", url, "\timg_url:", send_url, "\tcallback response:", jsonstr)
}
